package com.etone.smartAudit.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.etone.smartAudit.domain.Admin;
import com.etone.smartAudit.domain.BuildData;
import com.etone.smartAudit.dto.buildOn.BuildOnDto;
import com.etone.smartAudit.error.CustomParameterizedException;
import com.etone.smartAudit.mapper.BuildOnMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;

/***
 * 建审系统对应的service
 */
@Slf4j
@Service
public class BuildOnService {


    @Autowired
    private RestTemplateRequest request;
    @Value("${buildon.url:http://10.252.128.236:9080/interfaces/smartAuditApi!auditData.action}")
    private String url;

    @Value("${buildon.sysId:smartAudit}")
    private String sysId;

    @Value("${buildon.sysToken:smartAudit}")
    private String sysToken;


    @Value("${buildon.dataurl:local}")
    private String dataUrl;


    @Value("${buildon.toUrl:toUrl}")
    private String toUrl;

    @Autowired
    private BuildOnMapper buildOnMapper;


    /***
     * 获取当天所有的数据
     * @return
     */
    public List<BuildData> getList() {
        //获取最新的数据
        LambdaQueryWrapper<BuildData> query = new LambdaQueryWrapper<>();
        query.orderByDesc(BuildData::getId).last(" limit 1 ");
        BuildData lastData = buildOnMapper.selectOne(query);
        if (lastData == null) {
            //获取一次数据
            new Thread(() -> getBuildOn()).start();
            throw new CustomParameterizedException("暂无建审数据");
        }
        //获取当前的数据
        String groupId = lastData.getGroupid();
        //查询当前分组的数据是否存在
        LambdaQueryWrapper<BuildData> wapper = new LambdaQueryWrapper<>();
        wapper.eq(BuildData::getGroupid, groupId);
        List<BuildData> list = buildOnMapper.selectList(wapper);
        return list;
    }

    /***
     * 获取建审系统数据
     * @param admin
     * @param dto
     * @return
     */
    public String getBuildData(Admin admin, BuildOnDto dto) {

        if ("toUrl".equals(dto.getDataType())) {
            return toUrl;
        }

        //获取最新的数据
        LambdaQueryWrapper<BuildData> query = new LambdaQueryWrapper<>();
        query.eq(BuildData::getTypename, dto.getDataType());
        query.orderByDesc(BuildData::getId).last(" limit 1 ");
        BuildData lastData = buildOnMapper.selectOne(query);
        if (lastData == null) {
            throw new CustomParameterizedException("暂无建审数据");
        }
        //获取当前的数据
        String groupId = lastData.getGroupid();
        //查询当前分组的数据是否存在
        LambdaQueryWrapper<BuildData> wapper = new LambdaQueryWrapper<>();
        wapper.eq(BuildData::getGroupid, groupId);
        List<BuildData> list = buildOnMapper.selectList(wapper);
        if (CollectionUtil.isNotEmpty(list)) {
            try {
                BuildData data = list.stream().filter(bd -> bd.getTypename().equals(dto.getDataType())).findFirst().get();
                return data.getData();
            } catch (Exception e) {
                log.error("获取建审数据失败", e);
            }
        }
        //未获取到数据继续从对方获取
        String finalUrl = url + "?sysId=%s&sysToken=%s&dataType=%s";
        finalUrl = String.format(finalUrl, sysId, sysToken, dto.getDataType());
        Map<Object, Object> param = new HashMap<>();
        param.put("sysId", sysId);
        param.put("sysToken", sysToken);
        param.put("dataType", dto.getDataType());
        if ("local".equals(dataUrl)) {
            return getDataByKey(dto.getDataType());
        } else {
            StringBuilder data = new StringBuilder();
            request.get(param, finalUrl, result -> {
                data.append(result);
                //获取成功则保存到数据库
                BuildData bd = new BuildData();
                bd.setData(data.toString());
                bd.setTypename(dto.getDataType());
                bd.setCreatedTime(new Date());
                bd.setGroupid(groupId);
            });
            return data.toString();
        }
    }

    /***
     * 获取建审系统数据
     * @param dto
     * @return
     */
    public String requestData(BuildOnDto dto) {
        if ("toUrl".equals(dto.getDataType())) {
            return toUrl;
        }
        String finalUrl = url + "?sysId=%s&sysToken=%s&dataType=%s";
        finalUrl = String.format(finalUrl, sysId, sysToken, dto.getDataType());
        log.debug("请求url:{}",finalUrl);
        Map<Object, Object> param = new HashMap<>();
        param.put("sysId", sysId);
        param.put("sysToken", sysToken);
        param.put("dataType", dto.getDataType());
        if ("local".equals(dataUrl)) {
            return getDataByKey(dto.getDataType());
        } else {
            try {
                StringBuilder data = new StringBuilder();
                request.get(param, finalUrl, result -> {
                    data.append(result);
                });
                return data.toString();
            } catch (Exception e) {
                log.error("请求建设数据错误", e);
                return null;
            }

        }
    }

    /***
     * 获取建审数据 存储到数据库
     */
    @Async
    public void getBuildOn() {
        String[] tyeps = {"AuditTypeCount", "TopCompanyAuditCount", "TopCompanyAuditReduceRate"
                , "TopCompanyAuditReduceSumRate", "CompanyAuditMapData", "CompanyAuditKcData", "YearAuditCount"};
        String groupId = DigestUtil.md5Hex(DateUtil.format(new Date(), "yyyy-MM-dd"));
        //查询当前分组的数据是否存在
        LambdaQueryWrapper<BuildData> wapper = new LambdaQueryWrapper<>();
        wapper.eq(BuildData::getGroupid, groupId);
        List<BuildData> list = buildOnMapper.selectList(wapper);
        Map<String, Boolean> map = new HashMap<>();
        if (CollectionUtil.isNotEmpty(list)) {
            list.stream().forEach(bd -> {
                map.put(bd.getTypename(), true);
            });
        }
        for (String type : tyeps) {
            try {
                //判断是否获取到数据 如果已经拿过数据则不处理
                Boolean flag = map.get(type);

                BuildOnDto dto = new BuildOnDto();
                dto.setDataType(type);
                String data = requestData(dto);
                BuildData bd = new BuildData();
                bd.setData(data);
                bd.setTypename(type);
                bd.setCreatedTime(new Date());
                bd.setGroupid(groupId);
                Thread.sleep(1);
                //已经存在则更新
                if (flag != null && flag) {

                    //如果返回错误，则不更新
                    if (data != null) {

                        LambdaQueryWrapper<BuildData> query = new LambdaQueryWrapper();
                        query.eq(BuildData::getGroupid, groupId)
                                .eq(BuildData::getTypename, type);
                        buildOnMapper.update(bd, query);
                    }

                } else {
                    //插入
                    buildOnMapper.insert(bd);
                }
            } catch (Exception e) {
                log.error("插入数据错误", e);
            }
        }

    }

    public String getDataByKey(String dataType) {
        /**
         * 相关指标数据如下：
         * 1、总体审计水平TOP10：TopCompanyAuditReduceSumRate；
         * 2、地图上：
         * 广州分公司
         * 送审情况
         * 预算送审：XX
         * 结算送审：XX
         * 竣工决算送审：XX
         * 总体审计水平：XX%
         * 平均审减水平：XX%
         *
         * 勘查情况
         * 勘查APP使用占比：XX%
         * 勘查工单占比：XX%
         * 零差异率勘查占比：XX%；
         * 3、工单送审量统计，放两个指标：年度累计完成工单数、年度在途工单数；
         */
//        AuditTypeCount：总工单类型送审数量统计
//        TopCompanyAuditCount：公司送审量排行
//        TopCompanyAuditReduceRate：公司结算平均审减水平排行统计
//        TopCompanyAuditReduceSumRate：公司结算总体审计水平排行统计
//        CompanyAuditMapData：全省送审总体情况统计
//        CompanyAuditKcData：公司送审工单勘查情况统计
//        YearAuditCount：年度工单统计
        /**
         * 报表数据类型，可选值
         * AuditTypeCount：总工单类型送审数量统计
         * TopCompanyAuditCount：公司送审量排行
         * TopCompanyAuditReduceRate：公司结算平均审减水平排行统计
         * TopCompanyAuditReduceSumRate：公司结算总体审减水平排行统计
         * CompanyAuditMapData：全省送审总体情况统计
         * CompanyAuditKcData：公司送审工单勘查情况统计
         * YearAuditCount：年度工单统计
         */
        JSONObject obj = new JSONObject();
        obj.put("AuditTypeCount", "{\"dataList\":[[\"预算流程\",7],[\"结算流程\",59],[\"竣工决算审计流程\",10]],\"result\":\"success\"}");
        obj.put("TopCompanyAuditCount", "{\"dataList\":[[\"广州分公司\",54],[\"省公司\",18],[\"佛山分公司\",4]],\"result\":\"success\"}");
        obj.put("TopCompanyAuditReduceRate", "{\"dataList\":[[\"广州分公司\",0.0]],\"result\":\"success\"}");
        obj.put("TopCompanyAuditReduceSumRate", "{\"dataList\":[[\"广州分公司\",0.0]],\"result\":\"success\"}");
        obj.put("CompanyAuditMapData", "{\"result\":\"success\",\"TopReduceSumRateList\":[[\"广州分公司\",0.0]],\"TopReduceAvgRateList\":[[\"广州分公司\",0.0]],\"mapDataList\":[{\"jsCount\":9,\"name\":\"省公司\",\"reduceAvgRate\":0,\"reduceSumRate\":0,\"value\":18,\"ysCount\":5,\"nodiffPercent\":0,\"kcPercent\":0,\"jgjsCount\":4,\"appPercent\":0},{\"jsCount\":0,\"name\":\"江门分公司\",\"reduceAvgRate\":0,\"reduceSumRate\":0,\"value\":0,\"ysCount\":0,\"nodiffPercent\":0,\"kcPercent\":0,\"jgjsCount\":0,\"appPercent\":0},{\"jsCount\":0,\"name\":\"中国移动广东公司\",\"reduceAvgRate\":0,\"reduceSumRate\":0,\"value\":0,\"ysCount\":0,\"nodiffPercent\":0,\"kcPercent\":0,\"jgjsCount\":0,\"appPercent\":0},{\"jsCount\":0,\"name\":\"湛江分公司\",\"reduceAvgRate\":0,\"reduceSumRate\":0,\"value\":0,\"ysCount\":0,\"nodiffPercent\":0,\"kcPercent\":0,\"jgjsCount\":0,\"appPercent\":0},{\"jsCount\":0,\"name\":\"茂名分公司\",\"reduceAvgRate\":0,\"reduceSumRate\":0,\"value\":0,\"ysCount\":0,\"nodiffPercent\":0,\"kcPercent\":0,\"jgjsCount\":0,\"appPercent\":0},{\"jsCount\":0,\"name\":\"揭阳分公司\",\"reduceAvgRate\":0,\"reduceSumRate\":0,\"value\":0,\"ysCount\":0,\"nodiffPercent\":0,\"kcPercent\":0,\"jgjsCount\":0,\"appPercent\":0},{\"jsCount\":0,\"name\":\"韶关分公司\",\"reduceAvgRate\":0,\"reduceSumRate\":0,\"value\":0,\"ysCount\":0,\"nodiffPercent\":0,\"kcPercent\":0,\"jgjsCount\":0,\"appPercent\":0},{\"jsCount\":0,\"name\":\"河源分公司\",\"reduceAvgRate\":0,\"reduceSumRate\":0,\"value\":0,\"ysCount\":0,\"nodiffPercent\":0,\"kcPercent\":0,\"jgjsCount\":0,\"appPercent\":0},{\"jsCount\":0,\"name\":\"梅州分公司\",\"reduceAvgRate\":0,\"reduceSumRate\":0,\"value\":0,\"ysCount\":0,\"nodiffPercent\":0,\"kcPercent\":0,\"jgjsCount\":0,\"appPercent\":0},{\"jsCount\":0,\"name\":\"汕尾分公司\",\"reduceAvgRate\":0,\"reduceSumRate\":0,\"value\":0,\"ysCount\":0,\"nodiffPercent\":0,\"kcPercent\":0,\"jgjsCount\":0,\"appPercent\":0},{\"jsCount\":0,\"name\":\"阳江分公司\",\"reduceAvgRate\":0,\"reduceSumRate\":0,\"value\":0,\"ysCount\":0,\"nodiffPercent\":0,\"kcPercent\":0,\"jgjsCount\":0,\"appPercent\":0},{\"jsCount\":0,\"name\":\"肇庆分公司\",\"reduceAvgRate\":0,\"reduceSumRate\":0,\"value\":0,\"ysCount\":0,\"nodiffPercent\":0,\"kcPercent\":0,\"jgjsCount\":0,\"appPercent\":0},{\"jsCount\":46,\"name\":\"广州分公司\",\"reduceAvgRate\":0.0,\"reduceSumRate\":0.0,\"value\":54,\"ysCount\":2,\"nodiffPercent\":0,\"kcPercent\":6,\"jgjsCount\":6,\"appPercent\":0},{\"jsCount\":0,\"name\":\"清远分公司\",\"reduceAvgRate\":0,\"reduceSumRate\":0,\"value\":0,\"ysCount\":0,\"nodiffPercent\":0,\"kcPercent\":0,\"jgjsCount\":0,\"appPercent\":0},{\"jsCount\":0,\"name\":\"潮州分公司\",\"reduceAvgRate\":0,\"reduceSumRate\":0,\"value\":0,\"ysCount\":0,\"nodiffPercent\":0,\"kcPercent\":0,\"jgjsCount\":0,\"appPercent\":0},{\"jsCount\":0,\"name\":\"云浮分公司\",\"reduceAvgRate\":0,\"reduceSumRate\":0,\"value\":0,\"ysCount\":0,\"nodiffPercent\":0,\"kcPercent\":0,\"jgjsCount\":0,\"appPercent\":0},{\"jsCount\":0,\"name\":\"深圳分公司\",\"reduceAvgRate\":0,\"reduceSumRate\":0,\"value\":0,\"ysCount\":0,\"nodiffPercent\":0,\"kcPercent\":0,\"jgjsCount\":0,\"appPercent\":0},{\"jsCount\":0,\"name\":\"东莞分公司\",\"reduceAvgRate\":0,\"reduceSumRate\":0,\"value\":0,\"ysCount\":0,\"nodiffPercent\":0,\"kcPercent\":0,\"jgjsCount\":0,\"appPercent\":0},{\"jsCount\":4,\"name\":\"佛山分公司\",\"reduceAvgRate\":0,\"reduceSumRate\":0,\"value\":4,\"ysCount\":0,\"nodiffPercent\":0,\"kcPercent\":0,\"jgjsCount\":0,\"appPercent\":0},{\"jsCount\":0,\"name\":\"汕头分公司\",\"reduceAvgRate\":0,\"reduceSumRate\":0,\"value\":0,\"ysCount\":0,\"nodiffPercent\":0,\"kcPercent\":0,\"jgjsCount\":0,\"appPercent\":0},{\"jsCount\":0,\"name\":\"珠海分公司\",\"reduceAvgRate\":0,\"reduceSumRate\":0,\"value\":0,\"ysCount\":0,\"nodiffPercent\":0,\"kcPercent\":0,\"jgjsCount\":0,\"appPercent\":0},{\"jsCount\":0,\"name\":\"惠州分公司\",\"reduceAvgRate\":0,\"reduceSumRate\":0,\"value\":0,\"ysCount\":0,\"nodiffPercent\":0,\"kcPercent\":0,\"jgjsCount\":0,\"appPercent\":0},{\"jsCount\":0,\"name\":\"中山分公司\",\"reduceAvgRate\":0,\"reduceSumRate\":0,\"value\":0,\"ysCount\":0,\"nodiffPercent\":0,\"kcPercent\":0,\"jgjsCount\":0,\"appPercent\":0}]}");
        obj.put("CompanyAuditKcData", "{\"dataList\":[[\"广州分公司\",15,1,0,15,0]],\"result\":\"success\"}");
        obj.put("YearAuditCount", "{\"result\":\"success\",\"totalCount\":365,\"processCount\":306}");
        return obj.getString(dataType);
    }
}
